package com.aduerr.v1shouyin.unioncard;

import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;

import java.lang.ref.WeakReference;

/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2019/7/15 9:54
 * @change
 * @chang time
 * @class describe
 */

public class CustomSingleObserver<T> implements SingleObserver<T> {

    private final WeakReference<IView> viewWeakReference;

    private String message;

    public CustomSingleObserver(IView activity, String message) {
        viewWeakReference = new WeakReference<>(activity);
        this.message = message;
    }

    public CustomSingleObserver(IView activity) {
        this(activity, "交易处理中...");
    }

    public CustomSingleObserver(IView activity, boolean isNeedShow) {
        this(activity, isNeedShow ? "交易处理中..." : null);
    }


    @Override
    public void onSubscribe(Disposable d) {
        IView view = viewWeakReference.get();
        view.addDisposable(d);
        if(view != null && message != null) {
            view.showLoadingDialog(message);
        }
    }

    @Override
    public void onSuccess(T o) {
        IView view = viewWeakReference.get();
        if(view != null) {
            view.dismissLoadingDialog();
        }
    }

    @Override
    public void onError(Throwable e) {
        IView view = viewWeakReference.get();
        if(view != null && message != null) {
            view.dismissLoadingDialog();
        }
        handlerError(e);
    }

    public void handlerError(Throwable e) {
        e.printStackTrace();
    }
}
